const earthRadius = 6371008.8;

const earthCircumfrence = 2 * Math.PI * earthRadius; // meters

function circumferenceAtLatitude(latitude) {
	return earthCircumfrence * Math.cos((latitude * Math.PI) / 180);
}

function lngFromMercatorX(x) {
	return x * 360 - 180;
}

function latFromMercatorY(y) {
	const y2 = 180 - y * 360;
	return (360 / Math.PI) * Math.atan(Math.exp((y2 * Math.PI) / 180)) - 90;
}

function altitudeFromMercatorZ(z, y) {
	return z * circumferenceAtLatitude(latFromMercatorY(y));
}

export function cartographicFromMercator(x, y, z) {
	return {
		longitude: lngFromMercatorX(x),
		latitude: latFromMercatorY(y),
		height: altitudeFromMercatorZ(z, y)
	};
}
